package com.food.restaurantpro.fragments;

import java.util.Calendar;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;
import com.food.restaurantpro.activity.MainActivity;
import com.food.restaurantpro.adapters.ReservationArrayAdapter;
import com.food.restaurantpro.connection.DataHelper;
import com.food.restaurantpro.connection.DataResult;
import com.food.restaurantpro.connection.IServerService.Methods;
import com.food.restaurantpro.database.tables.ReservationTable;
import com.food.restaurantpro.objects.Reservation;
import com.food.restaurantpro.utils.AlertDialogInterface;
import com.food.restaurantpro.utils.Prefs;
import com.food.restaurantpro.utils.Utils;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class ReservationFragment extends Fragment implements OnClickListener, AlertDialogInterface {
	
	private TextView tvHeader;
	private TextView mTvDate;
	private TextView mTvTime;
	private TextView mTvPeoples;
	private boolean isProcessSubmit = false;
	private Reservation mReservation;
	private List<Reservation> mListReservation;
	private ListView mLvListReservation;
	private ReservationArrayAdapter mReservationArrayAdapter;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	private int mMinute;
	private int mHourOfDay;
	private Prefs mPref;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_reservation, container, false);
		
		tvHeader = (TextView) view.findViewById(R.id.tvHeader);
		if(tvHeader != null) {
			tvHeader.setText(R.string.reservation);
		}
		mTvDate = (TextView) view.findViewById(R.id.tvDateReservation);
		view.findViewById(R.id.btnEditDateReservation).setOnClickListener(this);
		mTvTime = (TextView) view.findViewById(R.id.tvTimeReservation);
		view.findViewById(R.id.btnEditTimeReservation).setOnClickListener(this);
		mTvPeoples = (TextView) view.findViewById(R.id.tvPeopleReservation);
		view.findViewById(R.id.btnEditPeopleReservation).setOnClickListener(this);
		mLvListReservation = (ListView) view.findViewById(R.id.lvListReservation);
		
		String memberCode = "anomynous";
		if(RestaurantApp.userInfo != null && !Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
			memberCode = RestaurantApp.userInfo.getGenerateId();
		}
		mListReservation = ReservationTable.getAllReservationsByMemberWithStatus(memberCode, "1");
		if(mListReservation != null && mListReservation.size() > 0) {
			view.findViewById(R.id.gl_image_item).setVisibility(View.GONE);
			view.findViewById(R.id.rl_ListReservation).setVisibility(View.VISIBLE);
		} else {
			view.findViewById(R.id.gl_image_item).setVisibility(View.VISIBLE);
			view.findViewById(R.id.rl_ListReservation).setVisibility(View.GONE);
		}
		
		mReservationArrayAdapter = new ReservationArrayAdapter(getActivity(), mListReservation, this);
		mLvListReservation.setAdapter(mReservationArrayAdapter);
		
		view.findViewById(R.id.tvReservationSubmit).setOnClickListener(this);
		view.findViewById(R.id.btnSubmitReservation).setOnClickListener(this);
		view.findViewById(R.id.tvReservationCancel).setOnClickListener(this);
		view.findViewById(R.id.btnCancelReservation).setOnClickListener(this);
		
		Calendar current = Calendar.getInstance(); 
		int day = current.get(Calendar.DAY_OF_MONTH);
		int month = current.get(Calendar.MONTH) + 1;
		int year = current.get(Calendar.YEAR);
		int hour = current.get(Calendar.HOUR_OF_DAY);
		int minute = current.get(Calendar.MINUTE);
		
		mPref = new Prefs(getActivity());
		mYear = mPref.getIntValue(0, Prefs.KEY_LAST_YEAR_PRE_ORDER);
		mMonth = mPref.getIntValue(0, Prefs.KEY_LAST_MONTH_PRE_ORDER);
		mDay = mPref.getIntValue(0, Prefs.KEY_LAST_DAY_PRE_ORDER);
		mHourOfDay = mPref.getIntValue(0, Prefs.KEY_LAST_HOUR_PRE_ORDER);
		mMinute = mPref.getIntValue(0, Prefs.KEY_LAST_MINUTE_PRE_ORDER);
		
		if ((mYear < year)
				|| (mYear == year && mMonth < month)
				|| (mYear == year && mMonth == month && mDay < day)
				|| (mYear == year && mMonth == month && mDay == day && mHourOfDay < hour)
				|| (mYear == year && mMonth == month && mDay == day && mHourOfDay == hour && mMinute < minute)) {
			//ngay gio pre-order cuoi cung < ngay gio hien tai
			//set ngay gio reservation =  ngay gio hien tai
			mYear = year;
			mMonth = month;
			mDay = day;
			mHourOfDay = hour;
			mMinute = minute;
		}
		
		mTvDate.setText(Utils.getStandardDate(mDay, mMonth, mYear));
		mTvTime.setText(Utils.getStandardTime(mHourOfDay, mMinute));
		mTvPeoples.setText("1");

		mTvDate.setOnClickListener(this);
		mTvTime.setOnClickListener(this);
		mTvPeoples.setOnClickListener(this);
		return view;
	}
	
	@Override
	public void onDestroy() {
		// TODO delete image and cache de giai phong bo nho
		super.onDestroy();
		Runtime.getRuntime().gc();
	}


	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tvDateReservation:
		case R.id.btnEditDateReservation:
			showDialogSelectDate();
			break;
		case R.id.tvTimeReservation:
		case R.id.btnEditTimeReservation:
			showDialogSelectTime();
			break;
		case R.id.tvPeopleReservation:
		case R.id.btnEditPeopleReservation:
			showDialogSelectPeople();
			break;
		case R.id.tvReservationSubmit:
		case R.id.btnSubmitReservation:
			submitReservation();
			break;
		case R.id.tvReservationCancel:
		case R.id.btnCancelReservation:
			((MainActivity)getActivity()).showSaleFragment();
			break;
		default:
			break;
		}
	}
	
	private void submitReservation() {
		if(isProcessSubmit) {
			return;
		}
		isProcessSubmit = true;
		mReservation = new Reservation();
		mReservation.setReservationDate(mTvDate.getText().toString());
		mReservation.setReservationTime(mTvTime.getText().toString());
		mReservation.setReservationNumber(mTvPeoples.getText().toString().split(" ")[0]);
		mReservation.setReservationStatus("1");
		if(!Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
			mReservation.setReservationMemberCode(RestaurantApp.userInfo.getGenerateId());
		} else {
			mReservation.setReservationMemberCode("anomynous");
		}
		DataHelper.getInstance().addObserver(new Observer() {
			@Override
			public void update(Observable observable, Object data) {
				// TODO Auto-generated method stub
				DataResult result = (DataResult) data;
				if (result.getMethodName().equals(Methods.submitReservation)) {
					((MainActivity)getActivity()).hideProcessDialog();
					String status = (String) result.getData();
					if(!Utils.isEmpty(status) && status.equals("true")) {
						/*Utils.showToast("You make reservation successfully");*/
						Toast.makeText(getActivity(), "You make reservation successfully", 7000).show();
						getListReservation();
					} else {
						Toast.makeText(getActivity(), "Submit fail", 7000).show();
					}
					isProcessSubmit = false;
					DataHelper.getInstance().deleteObserver(this);
				}
			}
		});
		((MainActivity)getActivity()).showProcessDialog(getString(R.string.processing_reservation));
		DataHelper.getInstance().submitReservation(mReservation);
	}
	
	private void getListReservation() {
		String userID = "anomynous";
		if(RestaurantApp.userInfo != null
				&& !Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
			userID = RestaurantApp.userInfo.getGenerateId();
		}
		DataHelper.getInstance().addObserver(new Observer() {
			@SuppressWarnings("unchecked")
			@Override
			public void update(Observable observable, Object data) {
				// TODO Auto-generated method stub
				DataResult result = (DataResult) data;
				if (result.getMethodName().equals(Methods.getListReservation)) {
					/*((MainActivity)getActivity()).hideProcessDialog();*/
					List<Reservation> list = (List<Reservation>) result.getData();
					ReservationTable.insertListReservations(list);
					updateDataUI(list);
					DataHelper.getInstance().deleteObserver(this);
				}
			}
		});
		/*((MainActivity)getActivity()).showProcessDialog();*/
		DataHelper.getInstance().getListReservation(userID);
	}
	
	private void updateDataUI(List<Reservation> list) {
		synchronized (mLvListReservation) {
			mListReservation = list;
			if(mListReservation != null && mListReservation.size() > 0) {
				getActivity().findViewById(R.id.gl_image_item).setVisibility(View.GONE);
				getActivity().findViewById(R.id.rl_ListReservation).setVisibility(View.VISIBLE);
			} else {
				getActivity().findViewById(R.id.gl_image_item).setVisibility(View.VISIBLE);
				getActivity().findViewById(R.id.rl_ListReservation).setVisibility(View.GONE);
			}
			mReservationArrayAdapter.setList(mListReservation);
			mReservationArrayAdapter.notifyDataSetChanged();
		}
	}
	
	private void showDialogSelectPeople() {
		AlertDialog.Builder builderSingle = new AlertDialog.Builder(
                getActivity());
        builderSingle.setIcon(R.drawable.phonatic_logo);
        builderSingle.setTitle("Select number people");
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.select_dialog_singlechoice);
        for(int i = 1; i < 11; i++) {
        	arrayAdapter.add("" + i);
        }
        builderSingle.setNegativeButton(getActivity().getString(R.string.cancel),
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builderSingle.setAdapter(arrayAdapter,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mTvPeoples.setText(arrayAdapter.getItem(which));
                    }
                });
        builderSingle.show();
	}

	private void showDialogSelectTime() {
		new TimePickerDialog(getActivity(), timePickerListener, mHourOfDay, mMinute, DateFormat.is24HourFormat(getActivity())).show();
	}

	private void showDialogSelectDate() {
		new DatePickerDialog(getActivity(), datePickerListener, mYear, mMonth - 1, mDay).show();
	}
	
	private TimePickerDialog.OnTimeSetListener timePickerListener = new OnTimeSetListener() {
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			mTvTime.setText(Utils.getStandardTime(hourOfDay, minute));
			mHourOfDay = hourOfDay;
			mMinute = minute;
		}
	};

	private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int selectedYear,int selectedMonth, int selectedDay) {
			mTvDate.setText(Utils.getStandardDate(selectedDay, selectedMonth + 1, selectedYear));
			mYear = selectedYear;
			mMonth = selectedMonth + 1;
			mDay = selectedDay;
		}
	};

	@Override
	public void onChooseYesCallback() {
		String memberCode = "anomynous";
		if(RestaurantApp.userInfo != null && !Utils.isEmpty(RestaurantApp.userInfo.getGenerateId())) {
			memberCode = RestaurantApp.userInfo.getGenerateId();
		}
		updateDataUI(ReservationTable.getAllReservationsByMemberWithStatus(memberCode, "1"));
	}

	@Override
	public void onChooseNoCallback() {
	}
}
